package us.sunrisemorning.pixivbrower.spider;

import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Aop;

import us.sunrisemorning.pixivbrower.Constants;
import us.sunrisemorning.pixivbrower.dao.ConfigService;
import us.sunrisemorning.pixivbrower.dao.IllustService;
import us.sunrisemorning.pixivbrower.dao.TagService;
import us.sunrisemorning.pixivbrower.model.Config;
import us.sunrisemorning.pixivbrower.model.Illust;

public class DbQueue implements Runnable {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private IllustService illustService = Aop.get(IllustService.class);
    private TagService tagService = Aop.get(TagService.class);
    private ConfigService configService = Aop.get(ConfigService.class);

    private LinkedBlockingQueue<JSONObject> queue = null;
    private Thread me = null;

    public boolean put(JSONObject obj) {
        try {
            queue.put(obj);
            return true;
        } catch (InterruptedException e) {
            logger.error("DbQueue put error.", e);
            return false;
        }
    }

    public int getSize() {
        return queue.size();
    }

    public synchronized void start() {
        if (me == null) {
            int cacheSize = configService.getIntegerConfig(Config.CACHE_SIZE);
            if (cacheSize > 0) {
                queue = new LinkedBlockingQueue<JSONObject>(cacheSize);
            } else {
                queue = new LinkedBlockingQueue<JSONObject>(Constants.DEFAULT_CACHE_SIZE);
            }
            me = new Thread(this);
            me.start();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                JSONObject o = queue.take();

                int illustId = o.getIntValue("illustId");
                String illustTitle = o.getString("illustTitle");
                int bookmarkCount = o.getIntValue("bookmarkCount");

                Illust illust = illustService.dao.findById(illustId);
                if (illust == null) {
                    illust = new Illust();
                    illust.setId(illustId);
                    illust.save();
                }
                illust.setTitle(illustTitle);
                illust.setBookmark(bookmarkCount);
                illust.update();

                tagService.updateTag(illustId, o.getJSONArray("tags"));
            } catch (Exception e) {
                logger.error("DbQueue error.", e);
            }
        }
    }

}
